import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Demo_ScanFile {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        //1.输入指定的目录
        System.out.println("请输入要扫描的目录：");
        String path = scanner.next();
        File file = new File(path);
        if(!file.exists()){
            System.out.println("目录不存在，请确认！");
            return;
        }
        if(!file.isDirectory()){
            System.out.println("输入的不是目录，请确认");
            return;
        }
        //2.输入要扫描的关键词
        System.out.println("请输入要扫描的关键词：");
        String word = scanner.next();
        //3.扫描目录
        List<File> fileList = new ArrayList<>();
        fileList = scanDir(file, word);
        for(File f : fileList){
            System.out.println(f.getAbsoluteFile());
        }
    }
    private static List<File> scanDir(File file, String word){
        File[] files = file.listFiles();
        if(files == null || files.length == 0){
            System.out.println("目录为空");
            return null;
        }
        List<File> fileList = new ArrayList<>();
        for(File f : files){
            //如果是文件
            if(f.isFile()){
                //扫描文件名
                if(f.getName().contains(word)){
                    fileList.add(f);
                }else{
                    //扫描文件内容
                    try(InputStream inputStream = new FileInputStream(f)){
                        Scanner scanner = new Scanner(inputStream);
                        StringBuilder stringBuilder = new StringBuilder();
                        while(scanner.hasNext()){
                            stringBuilder.append(scanner.next());
                        }
                        if(stringBuilder.indexOf(word) != -1){
                            fileList.add(f);
                        }
                    }catch(Exception e){
                        e.printStackTrace();
                    }
                }
            }
            //如果是目录 递归扫描
            if(f.isDirectory()){
                fileList.addAll(scanDir(f, word));
            }
        }
        return fileList;
    }
}
